package com.relytosoft.mizar.analyze.structure.services.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.relytosoft.dubhe.common.core.base.page.PageQuery;
import com.relytosoft.dubhe.common.core.exception.ServiceException;
import com.relytosoft.dubhe.common.elasticsearch.ElasticsearchUtil;
import com.relytosoft.dubhe.common.elasticsearch.page.PageResult;
import com.relytosoft.mizar.analyze.base.entity.pojo.dto.TaskRequestDto;
import com.relytosoft.mizar.analyze.base.enums.DeleteStatusEnum;
import com.relytosoft.mizar.analyze.base.enums.IndexNameTypeEnum;
import com.relytosoft.mizar.analyze.base.enums.TaskStatusEnum;
import com.relytosoft.mizar.analyze.common.utils.IndexUtil;
import com.relytosoft.mizar.analyze.structure.api.entity.AyStructureTask;
import com.relytosoft.mizar.analyze.structure.api.entity.AyStructureTaskSon;
import com.relytosoft.mizar.analyze.structure.api.pojo.dto.AyStructureTaskDto;
import com.relytosoft.mizar.analyze.structure.api.pojo.dto.AyStructureTaskUpdateDto;
import com.relytosoft.mizar.analyze.structure.api.pojo.dto.AyTaskIdDto;
import com.relytosoft.mizar.analyze.structure.api.pojo.query.AyStruMotorVehicleSearchQuery;
import com.relytosoft.mizar.analyze.structure.api.pojo.query.AyStruNonMotorVehicleSearchQuery;
import com.relytosoft.mizar.analyze.structure.api.pojo.query.AyStructurePersonSearchQuery;
import com.relytosoft.mizar.analyze.structure.api.pojo.query.AyStructureTaskQuery;
import com.relytosoft.mizar.analyze.structure.api.pojo.vo.AyBatchVo;
import com.relytosoft.mizar.analyze.structure.api.pojo.vo.AyCameraVo;
import com.relytosoft.mizar.analyze.structure.api.pojo.vo.AyStructureTaskVo;
import com.relytosoft.mizar.analyze.structure.services.mapper.AyStructureTaskMapper;
import com.relytosoft.mizar.analyze.structure.services.mapper.AyStructureTaskSonMapper;
import com.relytosoft.mizar.analyze.structure.services.service.AyStructureTaskService;
import com.relytosoft.mizar.analyze.structure.services.service.AyStructureTaskSonService;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: zyc
 * @version: v1.0
 * @description: com.relytosoft.mizar.analyze.structure.services.service.impl
 * @Date: 2022/5/12 15:44
 */
@Service
public class AyStructureTaskServiceImpl extends ServiceImpl<AyStructureTaskMapper, AyStructureTask> implements AyStructureTaskService {

    @Resource
    private AyStructureTaskMapper ayStructureTaskMapper;

    @Resource
    private AyStructureTaskSonMapper ayStructureTaskSonMapper;

    @Resource
    private AyStructureTaskSonService ayStructureTaskSonService;

    @Resource
    private ElasticsearchUtil elasticsearchUtil;


    @Override
    public IPage<AyStructureTaskVo> selectAyStructureTaskPageList(PageQuery pageQuery, AyStructureTaskQuery ayStructureTaskQuery) {
        if (StrUtil.isBlank(pageQuery.getOrderByColumn())) {
            pageQuery.setOrderByColumn("id");
            pageQuery.setIsAsc("desc");
        }
        return ayStructureTaskMapper.selectPageTaskList(pageQuery.build(), ayStructureTaskQuery);
    }

    @Override
    public boolean updateAyStructureTask(AyStructureTaskUpdateDto ayStructureTaskUpdateDto) {
        AyStructureTask ayStructureTask = getById(ayStructureTaskUpdateDto.getId());
        if (null != ayStructureTask && TaskStatusEnum.FINISHED.getValue() == ayStructureTask.getStatus()) {
            ayStructureTaskMapper.updateStructureTask(ayStructureTaskUpdateDto);
            return true;
        }
        throw new ServiceException("无法被修改的任务");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<TaskRequestDto> insertTaskWithSonWith(AyStructureTaskDto ayStructureTaskDto, AyStructureTask ayStructureTask) {
        boolean save = this.save(ayStructureTask);
        ArrayList<TaskRequestDto> taskRequestDtoS = new ArrayList<>();
        if (save) {
            for (AyCameraVo cameraVo : ayStructureTaskDto.getAyCameraVos()) {
                AyStructureTaskSon ayStructureTaskSon = new AyStructureTaskSon();
                ayStructureTaskSon.setCameraId(cameraVo.getCameraId());
                ayStructureTaskSon.setCameraName(cameraVo.getCameraName());
                ayStructureTaskSon.setVideoUrl(cameraVo.getVideoUrl());
                ayStructureTaskSon.setStructureTaskId(ayStructureTask.getId());
                ayStructureTaskSon.setTaskName(ayStructureTask.getName());
                ayStructureTaskSon.setStatus(ayStructureTask.getStatus());
                boolean saveSon = ayStructureTaskSonService.insertAyStructureTaskSon(ayStructureTaskSon);
                if (saveSon && TaskStatusEnum.CREATED.getValue() == ayStructureTask.getStatus()) {
                    taskRequestDtoS.add(ayStructureTaskSonService.createRequest(ayStructureTaskSon));
                    continue;
                }
            }
            return taskRequestDtoS;
        }
        throw new ServiceException("创建结构化任务失败");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<TaskRequestDto> startAyStructureTask(AyTaskIdDto ayTaskIdDto, AyStructureTask ayStructureTask, List<AyStructureTaskSon> ayStructureTaskSons) {
        ayStructureTask.setStatus(TaskStatusEnum.RUNING.getValue());
        ayStructureTask.setUpdatedBy(ayTaskIdDto.getUpdatedBy());
        ayStructureTask.setUpdatedId(ayTaskIdDto.getUpdatedId());
        ayStructureTask.setBeginTime(LocalDateTime.now());
        ayStructureTask.setEndTime(null);
        boolean update = this.updateById(ayStructureTask);
        ArrayList<TaskRequestDto> taskRequestDtoS = new ArrayList<>();
        if (update) {
            for (AyStructureTaskSon taskSon : ayStructureTaskSons) {
                boolean startSon = ayStructureTaskSonService.startAyStructureTaskSon(ayTaskIdDto, taskSon);
                if (startSon) {
                    taskRequestDtoS.add(ayStructureTaskSonService.createRequest(taskSon));
                    continue;
                }
            }
            return taskRequestDtoS;
        }
        throw new ServiceException("启动结构化分析任务失败");

    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<String> stopAyStructureTask(AyTaskIdDto ayTaskIdDto, AyStructureTask ayStructureTask, List<AyStructureTaskSon> ayStructureTaskSons) {
        ayStructureTask.setStatus(TaskStatusEnum.FINISHED.getValue());
        ayStructureTask.setUpdatedBy(ayTaskIdDto.getUpdatedBy());
        ayStructureTask.setUpdatedId(ayTaskIdDto.getUpdatedId());
        ayStructureTask.setEndTime(LocalDateTime.now());
        boolean update = this.updateById(ayStructureTask);
        List<String> taskIds = new ArrayList<>();
        if (update) {
            for (AyStructureTaskSon taskSon : ayStructureTaskSons) {
                boolean stopSon = ayStructureTaskSonService.stopAyStructureTaskSon(ayTaskIdDto, taskSon);
                if (stopSon) {
                    taskIds.add(taskSon.getTaskId());
                    continue;
                }
            }
            return taskIds;
        }
        throw new ServiceException("停止结构化分析任务失败");

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteTaskWithSonWith(AyTaskIdDto ayTaskIdDto) {
        int updatedId = ayTaskIdDto.getUpdatedId();
        String updatedBy = ayTaskIdDto.getUpdatedBy();
        List<Integer> ids = ayTaskIdDto.getIds();

        for (Integer id : ids) {
            AyStructureTask task = getById(id);
            task.setUpdatedBy(updatedBy);
            task.setUpdatedId(updatedId);
            task.setIsDeleted(DeleteStatusEnum.DELETED.getValue());
            if (updateById(task)) {
                List<Integer> sonIds = ayStructureTaskSonMapper.selectSonIds(task.getId());
                ayTaskIdDto.setIds(sonIds);
                ayStructureTaskSonService.updateAyStructureTaskSon(ayTaskIdDto);
            }
        }
    }

    @Override
    public JSONObject personResultSearch(AyStructurePersonSearchQuery structurePersonSearchQuery, PageQuery pageQuery) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        String index = IndexUtil.toMonthIndex(IndexNameTypeEnum.AY_STRUCTURE_PERSON.getMessage());
        if (null != structurePersonSearchQuery.getDataType() && "PERSON".equals(structurePersonSearchQuery.getDataType())) {
            boolQueryBuilder.must(QueryBuilders.termQuery("dataType", structurePersonSearchQuery.getDataType()));
        }
        if (null != structurePersonSearchQuery.getStructureTaskId()) {
            boolQueryBuilder.must(QueryBuilders.termsQuery("structureTaskId", new int[]{structurePersonSearchQuery.getStructureTaskId()}));
        }
        if (null != structurePersonSearchQuery.getAge()) {
            boolQueryBuilder.must(QueryBuilders.termsQuery("age", structurePersonSearchQuery.getAge().split(",")));
        }
        if (null != structurePersonSearchQuery.getTrousersColor()) {
            boolQueryBuilder.must(QueryBuilders.termsQuery("trousersColor", structurePersonSearchQuery.getTrousersColor().split(",")));
        }
        if (null != structurePersonSearchQuery.getGenderCode()) {
            boolQueryBuilder.must(QueryBuilders.termsQuery("genderCode", structurePersonSearchQuery.getGenderCode().split(",")));
        }
        if (null != structurePersonSearchQuery.getCoatStyle()) {
            boolQueryBuilder.must(QueryBuilders.termsQuery("coatStyle", structurePersonSearchQuery.getCoatStyle().split(",")));
        }
        if (null != structurePersonSearchQuery.getCoatColor()) {
            boolQueryBuilder.must(QueryBuilders.termsQuery("coatColor", structurePersonSearchQuery.getCoatColor().split(",")));
        }
        if (null != structurePersonSearchQuery.getCoatLength()) {
            boolQueryBuilder.must(QueryBuilders.termsQuery("coatLength", structurePersonSearchQuery.getCoatLength().split(",")));
        }
        if (null != structurePersonSearchQuery.getTrousersStyle()) {
            boolQueryBuilder.must(QueryBuilders.termsQuery("trousersStyle", structurePersonSearchQuery.getTrousersStyle().split(",")));
        }
        if (null != structurePersonSearchQuery.getTrousersColor()) {
            boolQueryBuilder.must(QueryBuilders.termsQuery("trousersColor", structurePersonSearchQuery.getTrousersColor().split(",")));
        }
        if (null != structurePersonSearchQuery.getTrousersLength()) {
            boolQueryBuilder.must(QueryBuilders.termsQuery("trousersLength", structurePersonSearchQuery.getTrousersLength().split(",")));
        }
        if (null != structurePersonSearchQuery.getDeviceId()) {
            boolQueryBuilder.must(QueryBuilders.termsQuery("deviceId", structurePersonSearchQuery.getDeviceId().split(",")));
        }
        if (null != structurePersonSearchQuery.getBeginTime()) {
            boolQueryBuilder.must(QueryBuilders.rangeQuery("markTime").gte(structurePersonSearchQuery.getBeginTime().getTime()));
        }
        if (null != structurePersonSearchQuery.getEndTime()) {
            boolQueryBuilder.must(QueryBuilders.rangeQuery("markTime").lte(structurePersonSearchQuery.getEndTime().getTime()));
        }

        try {
            PageResult pageResult = elasticsearchUtil.searchPage(pageQuery, new String[]{index}, boolQueryBuilder);
            return JSON.parseObject(JSON.toJSONString(pageResult));
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return null;
    }

    @Override
    public JSONObject motorVehicleResultSearch(AyStruMotorVehicleSearchQuery struMotorVehicleSearchQuery, PageQuery pageQuery) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        String index = IndexUtil.toMonthIndex(IndexNameTypeEnum.AY_STRUCTURE_MOTOR_VEHICLE.getMessage());
        if (null != struMotorVehicleSearchQuery.getDataType() && "MOTOR_VEHICLE".equals(struMotorVehicleSearchQuery.getDataType())) {
            boolQueryBuilder.must(QueryBuilders.termQuery("dataType", struMotorVehicleSearchQuery.getDataType()));
        }
        if (null != struMotorVehicleSearchQuery.getStructureTaskId()) {
            boolQueryBuilder.must(QueryBuilders.termsQuery("structureTaskId", new int[]{struMotorVehicleSearchQuery.getStructureTaskId()}));
        }
        if (null != struMotorVehicleSearchQuery.getDeviceId()) {
            boolQueryBuilder.must(QueryBuilders.termsQuery("deviceId", struMotorVehicleSearchQuery.getDeviceId().split(",")));
        }
        if (null != struMotorVehicleSearchQuery.getBeginTime()) {
            boolQueryBuilder.must(QueryBuilders.rangeQuery("markTime").gte(struMotorVehicleSearchQuery.getBeginTime().getTime()));
        }
        if (null != struMotorVehicleSearchQuery.getEndTime()) {
            boolQueryBuilder.must(QueryBuilders.rangeQuery("markTime").lte(struMotorVehicleSearchQuery.getEndTime().getTime()));
        }
        if (null != struMotorVehicleSearchQuery.getVehicleBrand()) {
            boolQueryBuilder.must(QueryBuilders.termsQuery("vehicleBrand", struMotorVehicleSearchQuery.getVehicleBrand().split(",")));
        }
        if (null != struMotorVehicleSearchQuery.getVehicleColor()) {
            boolQueryBuilder.must(QueryBuilders.termsQuery("vehicleColor", struMotorVehicleSearchQuery.getVehicleColor().split(",")));
        }
        if (null != struMotorVehicleSearchQuery.getVehicleModel()) {
            boolQueryBuilder.must(QueryBuilders.termsQuery("vehicleModel", struMotorVehicleSearchQuery.getVehicleModel().split(",")));
        }
        if (null != struMotorVehicleSearchQuery.getVehicleStyles()) {
            boolQueryBuilder.must(QueryBuilders.termsQuery("vehicleStyles", struMotorVehicleSearchQuery.getVehicleStyles().split(",")));
        }
        if (null != struMotorVehicleSearchQuery.getPlateNo()) {
            boolQueryBuilder.must(QueryBuilders.termsQuery("plateNo", struMotorVehicleSearchQuery.getPlateNo().split(",")));
        }
        if (null != struMotorVehicleSearchQuery.getPlateClass()) {
            boolQueryBuilder.must(QueryBuilders.termsQuery("plateClass", struMotorVehicleSearchQuery.getPlateClass().split(",")));
        }
        try {
            PageResult pageResult = elasticsearchUtil.searchPage(pageQuery, new String[]{index}, boolQueryBuilder);
            return JSON.parseObject(JSON.toJSONString(pageResult));
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return null;
    }

    @Override
    public JSONObject nonMotorVehicleResultSearch(AyStruNonMotorVehicleSearchQuery ayStruNonMotorVehicleSearchQuery, PageQuery pageQuery) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        String index = IndexUtil.toMonthIndex(IndexNameTypeEnum.AY_STRUCTURE_PERSON.getMessage());
        if (null != ayStruNonMotorVehicleSearchQuery.getDataType() && "NON_MOTOR_VEHICLE".equals(ayStruNonMotorVehicleSearchQuery.getDataType())) {
            boolQueryBuilder.must(QueryBuilders.termQuery("dataType", ayStruNonMotorVehicleSearchQuery.getDataType()));
        }
        if (null != ayStruNonMotorVehicleSearchQuery.getStructureTaskId()) {
            boolQueryBuilder.must(QueryBuilders.termsQuery("structureTaskId", new int[]{ayStruNonMotorVehicleSearchQuery.getStructureTaskId()}));
        }
        if (null != ayStruNonMotorVehicleSearchQuery.getDeviceId()) {
            boolQueryBuilder.must(QueryBuilders.termsQuery("deviceId", ayStruNonMotorVehicleSearchQuery.getDeviceId().split(",")));
        }
        if (null != ayStruNonMotorVehicleSearchQuery.getBeginTime()) {
            boolQueryBuilder.must(QueryBuilders.rangeQuery("markTime").gte(ayStruNonMotorVehicleSearchQuery.getBeginTime().getTime()));
        }
        if (null != ayStruNonMotorVehicleSearchQuery.getEndTime()) {
            boolQueryBuilder.must(QueryBuilders.rangeQuery("markTime").lte(ayStruNonMotorVehicleSearchQuery.getEndTime().getTime()));
        }

        try {
            PageResult pageResult = elasticsearchUtil.searchPage(pageQuery, new String[]{index}, boolQueryBuilder);
            return JSON.parseObject(JSON.toJSONString(pageResult));
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return null;
    }

    @Override
    public JSONObject integratedSearch(AyStruNonMotorVehicleSearchQuery ayStruNonMotorVehicleSearchQuery, PageQuery pageQuery) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        String index = IndexUtil.toMonthIndex(IndexNameTypeEnum.AY_STRUCTURE_PERSON.getMessage());
        if (null != ayStruNonMotorVehicleSearchQuery.getDataType()) {
            boolQueryBuilder.must(QueryBuilders.termQuery("dataType", ayStruNonMotorVehicleSearchQuery.getDataType()));
        }
        if (null != ayStruNonMotorVehicleSearchQuery.getStructureTaskId()) {
            boolQueryBuilder.must(QueryBuilders.termsQuery("structureTaskId", new int[]{ayStruNonMotorVehicleSearchQuery.getStructureTaskId()}));
        }
        if (null != ayStruNonMotorVehicleSearchQuery.getDeviceId()) {
            boolQueryBuilder.must(QueryBuilders.termsQuery("deviceId", ayStruNonMotorVehicleSearchQuery.getDeviceId().split(",")));
        }
        if (null != ayStruNonMotorVehicleSearchQuery.getBeginTime()) {
            boolQueryBuilder.must(QueryBuilders.rangeQuery("markTime").gte(ayStruNonMotorVehicleSearchQuery.getBeginTime().getTime()));
        }
        if (null != ayStruNonMotorVehicleSearchQuery.getEndTime()) {
            boolQueryBuilder.must(QueryBuilders.rangeQuery("markTime").lte(ayStruNonMotorVehicleSearchQuery.getEndTime().getTime()));
        }

        try {
            PageResult pageResult = elasticsearchUtil.searchPage(pageQuery, new String[]{index}, boolQueryBuilder);
            return JSON.parseObject(JSON.toJSONString(pageResult));
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return null;
    }

    @Override
    public AyBatchVo insertTaskByDto(AyStructureTaskDto ayStructureTaskDto) {
        //所有需要添加的设备id
        List<AyCameraVo> ayCameraVos = ayStructureTaskDto.getAyCameraVos();

        AyBatchVo ayBatchVo = new AyBatchVo();
        ayBatchVo.setTotal(ayCameraVos.size());
        //没有符合条件的设备
        if (addFrontVerify(ayStructureTaskDto)) {
            ayBatchVo.setSuccess(0);
            ayBatchVo.setError(ayCameraVos.size());
            ayBatchVo.setErrorMsg(Collections.singletonList("没有符合创建条件的设备"));
            return ayBatchVo;
        }
        AyStructureTask ayStructureTask = AyStructureTaskDto.buildAddTask(ayStructureTaskDto);
        List<TaskRequestDto> taskRequestDtoS = insertTaskWithSonWith(ayStructureTaskDto, ayStructureTask);
        taskRequestDtoS.stream().forEach(a -> ayStructureTaskSonService.insertStructureTaskSonKafkaOpMsg(a));

        ayBatchVo.setSuccess(taskRequestDtoS.size());
        ayBatchVo.setError(ayCameraVos.size() - taskRequestDtoS.size());
        ayBatchVo.setErrorMsg(Collections.singletonList("符合条件的任务已添加成功"));

        return ayBatchVo;
    }

    /**
     * 结构化任务添加前置验证
     *
     * @param ayStructureTaskDto
     * @return
     */
    public Boolean addFrontVerify(AyStructureTaskDto ayStructureTaskDto) {
        Integer id = ayStructureTaskMapper.selectStructureTaskId(ayStructureTaskDto.getName());
        if (null != id) {
            throw new ServiceException("创建任务发生错误：任务名已存在");
        }
        List<AyCameraVo> ayCameraVos = ayStructureTaskDto.getAyCameraVos();
        //所有需要添加的设备ids
        if (ayCameraVos.isEmpty()) {
            return false;
        }
        Iterator<AyCameraVo> cameraVoIterator = ayCameraVos.iterator();
        while (cameraVoIterator.hasNext()) {
            AyCameraVo cameraVo = cameraVoIterator.next();
            List<AyStructureTaskSon> taskSons = ayStructureTaskSonService.list(new LambdaQueryWrapper<AyStructureTaskSon>()
                    .eq(AyStructureTaskSon::getCameraId, cameraVo.getCameraId())
                    .eq(AyStructureTaskSon::getIsDeleted, DeleteStatusEnum.NOT_DELETED.getValue()));
            if (!taskSons.isEmpty()) {
                //过滤已经存在的camera
                cameraVoIterator.remove();
            }
        }
        return ayCameraVos.isEmpty();
    }

    /**
     * 结构化任务删除前置验证
     *
     * @param ids 主任务集合
     * @return
     */
    public Boolean deleteTaskFrontVerify(List<Integer> ids) {
        if (ids.isEmpty()) {
            return false;
        }
        Iterator<Integer> iterator = ids.iterator();
        while (iterator.hasNext()) {
            Integer id = iterator.next();
            AyStructureTask task = getById(id);
            //任务id不正确
            if (Objects.isNull(task)) {
                iterator.remove();
                continue;
            }
            //任务状态为运行中  或者删除状态已删除 不符合条件
            if (TaskStatusEnum.RUNING.getValue() == task.getStatus()
                    ||
                    DeleteStatusEnum.DELETED.getValue() == task.getIsDeleted()) {
                iterator.remove();
            }
        }
        if (ids.isEmpty()) {
            return false;
        }
        return true;
    }

    /**
     * 结构化任务子任务删除前置验证
     *
     * @param id 主任务id
     * @return
     */
    public Boolean deleteSonTaskFrontVerify(Integer id) {
        List<AyStructureTaskSon> ayStructureTaskSons = ayStructureTaskSonService.selectByStructureTaskId(id);
        Iterator<AyStructureTaskSon> sonIterator = ayStructureTaskSons.iterator();
        while (sonIterator.hasNext()) {
            AyStructureTaskSon taskSon = sonIterator.next();
            Integer status = taskSon.getStatus();
            Integer isDeleted = taskSon.getIsDeleted();
            if (Objects.equals(status, TaskStatusEnum.RUNING.getValue()) || Objects.equals(isDeleted, DeleteStatusEnum.DELETED.getValue())) {
                return false;
            }
        }
        return true;
    }

    @Override
    public Boolean deleteTaskByIds(AyTaskIdDto ayTaskIdDto) {
        List<Integer> ids = ayTaskIdDto.getIds();
        //主任务删除验证
        if (!deleteTaskFrontVerify(ids)) {
            return false;
        }
        //子任务删除验证
        List<Integer> verifyIds = ids.stream().filter(id -> !deleteSonTaskFrontVerify(id)).collect(Collectors.toList());
        if (verifyIds.isEmpty()) {
            return false;
        }

        deleteTaskWithSonWith(ayTaskIdDto);
        return true;
    }

    @Override
    public Boolean startTaskByIds(AyTaskIdDto ayTaskIdDto) {
        List<Integer> ids = ayTaskIdDto.getIds();
        //主任务验证
        if (!startTaskFrontVerify(ids)) {
            return false;
        }
        //子任务验证
        List<Integer> verifyIds = ids.stream().filter(id -> !deleteSonTaskFrontVerify(id)).collect(Collectors.toList());
        if (verifyIds.isEmpty()) {
            return false;
        }
        List<AyStructureTask> ayStructureTasks = this.listByIds(ayTaskIdDto.getIds());
        for (AyStructureTask task : ayStructureTasks) {
            List<AyStructureTaskSon> ayStructureTaskSons = ayStructureTaskSonService.selectByStructureTaskId(task.getId());
            List<TaskRequestDto> taskRequestDtoS = startAyStructureTask(ayTaskIdDto, task, ayStructureTaskSons);
            taskRequestDtoS.stream().forEach(item -> ayStructureTaskSonService.insertStructureTaskSonKafkaOpMsg(item));
        }
        return true;
    }


    @Override
    public Boolean stopTaskByIds(AyTaskIdDto ayTaskIdDto) {
        List<Integer> ids = ayTaskIdDto.getIds();
        //主任务验证
        if (!stopTaskFrontVerify(ids)) {
            return false;
        }
        //子任务验证
        List<Integer> verifyIds = ids.stream().filter(id -> !stopSonTaskFrontVerify(id)).collect(Collectors.toList());
        if (verifyIds.isEmpty()) {
            return false;
        }
        List<AyStructureTask> ayStructureTasks = this.listByIds(ayTaskIdDto.getIds());
        for (AyStructureTask task : ayStructureTasks) {
            List<AyStructureTaskSon> ayStructureTaskSons = ayStructureTaskSonService.selectByStructureTaskId(task.getId());
            List<String> taskIds = stopAyStructureTask(ayTaskIdDto, task, ayStructureTaskSons);
            taskIds.stream().forEach(item -> ayStructureTaskSonService.deleteStructureTaskSonKafkaOpMsg(item));
        }
        return true;
    }


    private Boolean startTaskFrontVerify(List<Integer> ids) {
        if (ids.isEmpty()) {
            return false;
        }
        Iterator<Integer> iterator = ids.iterator();
        while (iterator.hasNext()) {
            Integer id = iterator.next();
            AyStructureTask task = getById(id);
            //任务id不正确
            if (Objects.isNull(task)) {
                iterator.remove();
                continue;
            }
            //任务状态为运行中  或者删除状态已删除 不符合条件
            if (TaskStatusEnum.RUNING.getValue() == task.getStatus()
                    ||
                    DeleteStatusEnum.DELETED.getValue() == task.getIsDeleted()) {
                iterator.remove();
            }
        }
        if (ids.isEmpty()) {
            return false;
        }
        return true;
    }


    private Boolean stopTaskFrontVerify(List<Integer> ids) {
        if (ids.isEmpty()) {
            return false;
        }
        Iterator<Integer> iterator = ids.iterator();
        while (iterator.hasNext()) {
            Integer id = iterator.next();
            AyStructureTask task = getById(id);
            //任务id不正确
            if (Objects.isNull(task)) {
                iterator.remove();
                continue;
            }
            //任务状态不为运行中  或者删除状态已删除 不符合条件
            if (TaskStatusEnum.RUNING.getValue() != task.getStatus()
                    ||
                    DeleteStatusEnum.DELETED.getValue() == task.getIsDeleted()) {
                iterator.remove();
            }
        }
        if (ids.isEmpty()) {
            return false;
        }
        return true;
    }

    /**
     * 结构化任务子任务停止前置验证
     *
     * @param id 主任务id
     * @return
     */
    public Boolean stopSonTaskFrontVerify(Integer id) {
        List<AyStructureTaskSon> ayStructureTaskSons = ayStructureTaskSonService.selectByStructureTaskId(id);
        Iterator<AyStructureTaskSon> sonIterator = ayStructureTaskSons.iterator();
        while (sonIterator.hasNext()) {
            AyStructureTaskSon taskSon = sonIterator.next();
            Integer status = taskSon.getStatus();
            Integer isDeleted = taskSon.getIsDeleted();
            if (Objects.equals(status, TaskStatusEnum.RUNING.getValue()) && Objects.equals(isDeleted, DeleteStatusEnum.NOT_DELETED.getValue())) {
                return false;
            }
        }
        return true;
    }


}
